package com.zzn.bookManage.service.impl;

import com.zzn.bookManage.dao.UserDao;
import com.zzn.bookManage.dao.impl.UserDaoImpl;
import com.zzn.bookManage.pojo.User;
import com.zzn.bookManage.service.UserService;
import com.zzn.bookManage.util.StringUtil;

import java.util.List;

public class UserServiceImpl implements UserService {
    private static final UserDao userDao = new UserDaoImpl();

    @Override
    public User registerUser(User in) {
        // 非空校验
        if (in == null || StringUtil.isBlank(in.getUsername()) ||
                StringUtil.isBlank(in.getPassword()) ||
                StringUtil.isBlank(in.getNickname())
        ) {
            return null;
        }
        if (userDao.addUser(in)){
            // 插入成功后取回当前用户信息
            List<User> users = userDao.listUsersByUsername(in);
            users.get(0).setPassword("");
            return users.get(0);
        }
        return null;
    }

    @Override
    public User loginUser(User in) {
        // 非空校验
        if (in == null || StringUtil.isBlank(in.getUsername())) {
            return null;
        }
        List<User> users = userDao.listUsersByUsername(in);
        // 用户唯一且密码正确
        if (users.size() != 1 || !users.get(0).getPassword().equals(in.getPassword())) {
            return null;
        }
        users.get(0).setPassword("");
        return users.get(0);
    }

    @Override
    public boolean deleteUser(User in) {
        if (in == null || in.getUid() == null) {
            return false;
        }
        return userDao.deleteUser(in);
    }

    @Override
    public List<User> listUsers() {
        return userDao.listUsers();
    }

    @Override
    public List<User> listUsersByNickname(User in) {
        if (StringUtil.isBlank(in.getNickname())) {
            return null;
        }
        return userDao.listUsersByUsername(in);
    }

    @Override
    public boolean changeUserInfo(User in) {
        if (in == null || in.getUid() == null || StringUtil.isBlank(in.getNickname())) {
            return false;
        }
        return userDao.updateUserInfo(in);
    }

    @Override
    public boolean changeUserPassword(User in) {
        if (in == null || in.getUid() == null || StringUtil.isBlank(in.getPassword())) {
            return false;
        }
        return userDao.updateUserPassword(in);
    }
}
